package gold.enterprise;

import java.util.Stack;

public class CoupanTwice {

    //    1. Given a an expression string, calculate the result of the expression.
//            for example:
//            1 + 2 - 3 + 5
//            -2+5 - 3
//
//    follow up:
//    what if brackets are also allowed in the input string.
    public int basicCalculator(String s) {
        Stack<Integer> numStack = new Stack<>();
        char lastOp = '+';//假设默认是+号

        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            char curChar = arr[i];
            if (curChar == ' ') continue;    //skip white char
            if (Character.isDigit(curChar)) {
                int tempNum = curChar - '0';
                while (++i < arr.length && Character.isDigit(arr[i])) {
                    tempNum = tempNum * 10 + arr[i] - '0';
                }
                --i;

                if (lastOp == '+') numStack.push(tempNum);
                else if (lastOp == '-') numStack.push(-tempNum);
                else numStack.push(doCalculate(lastOp, numStack.pop(), tempNum));
            } else {
                // current meet operate char
                lastOp = curChar;
            }
        }

        int result = 0;
        for (Integer num : numStack) {
            result += num;
        }

        return result;
    }

    private int doCalculate(char op, int a, int b) {
        if (op == '*') return a * b;
        else if (op == '/') return a / b;//shall throw numExceiton;
        else if (op == '+') return a + b;
        return a - b;   //default return subtracte
    }


//2. Find longest substring without repeating characters
//
//    Input: "abcabcbb" / Output: 3
//    Explanation: The answer is "abc", with the length of 3.
//
//    Input: "bbbbb" / Output: 1
//    Explanation: The answer is "b", with the length of 1.
//
//    Input: "pwwkew" / Output: 3
//    Explanation: The answer is "wke", with the length of 3.



    public static void main(String[] args) {
        CoupanTwice solution = new CoupanTwice();
        System.out.println(solution.basicCalculator("      0/5   -2       +5 - 3"));
    }


}



